class Node{
  constructor(element,next){
    this.element=element;
    this.next=next || null;
  }
}
class MyLinkedList{
  constructor(){
    this.size=0;
    this.head=null;
    this.last=null;
  }
  insert(index,element){
    if (index<0 || index>this.size) {
      throw new Error("超出链表节点范围！");
    }
    let insertedNode = new Node(element);
    if(this.size===0){
      //空链表
      this.head=insertedNode
      this.last=insertedNode
    }else if(index===0){
      //插入头部
      insertedNode.next=this.head;
      this.head=insertedNode
    }else if(this.size === index){
       //插入尾部
       this.last.next=insertedNode
       this.last = insertedNode;
    }else{
       //插入中间
       let  prevNode = this.get(index-1);
       insertedNode.next = prevNode.next;
       prevNode.next = insertedNode;
    }
    this.size++;
  }
  remove(index){
    if (index<0 || index>this.size) {
      throw new Error("超出链表节点范围！");
    }
    if(index===0){
      //删除头节点
      if(this.size===1){
        this.head=null
      }else{
        this.head=this.head.next
      }
    }else if(index===this.size-1){
      //删除尾节点
      let prevNode = this.get(index-1);
      prevNode.next = null;
      this.last=prevNode;
    }else {
      let prevNode = this.get(index-1);
      let nextNode = prevNode.next.next;
      prevNode.next = nextNode;
    }
    this.size--;
  }
  get(index){
    if (index<0 || index>=this.size) {
      throw new Error("超出链表节点范围！");
    }
    let temp=this.head
    for (let i = 0; i < index; i++) {
      temp = temp.next;
    }
    return temp
  }
  output(){
    let temp=this.head;
    while (temp!==null) {
      console.log(temp.element)
      temp = temp.next;
  }
  }
}

const myLinkedList = new MyLinkedList();

myLinkedList.insert(0,3);
myLinkedList.insert(0,4); //头插入
myLinkedList.insert(1,6); //中间插入
myLinkedList.insert(2,9); //中间插入
myLinkedList.insert(3,5); //中间插入
myLinkedList.remove(0);
myLinkedList.output();

console.log(JSON.stringify(myLinkedList,2))